<?php

namespace app\admin\service;

use app\admin\cache\FileUploadConfigCache;
use app\admin\model\FileUploadConfig;
use common\enum\ResultCode;
use Tinywan\ExceptionHandler\Exception\NotFoundHttpException;

class FileUploadConfigService extends BaseCurdService
{
    /**
     * 获取配置详情
     * @param int $id 配置ID
     * @return FileUploadConfig|null
     */
    public function getInfo(int $id): ?FileUploadConfig
    {
        $config = FileUploadConfig::find($id);
        if (!$config) {
            throw new NotFoundHttpException(ResultCode::DATA_NOT_FOUND->getDescription());
        }
        return $config;
    }

    /**
     * 更新配置
     * @param int $id 配置ID
     * @param array $data 配置数据
     * @return bool
     */
    public function update(int $id, array $data): bool
    {
        $config = FileUploadConfig::find($id);
        if (!$config) {
            throw new NotFoundHttpException(ResultCode::DATA_NOT_FOUND->getDescription());
        }
        // 移除不允许更新的字段
        unset($data['name'], $data['storage_type']);
        // 如果要启用此配置，需要先禁用其他配置
        if (isset($data['status']) && $data['status'] == 1) {
            FileUploadConfig::where('id', '<>', $id)->update(['status' => 0]);
        }
        // 处理配置字段
        if (isset($data['config']) && is_string($data['config'])) {
            $data['config'] = json_decode($data['config'], true);
        }
        $result = $config->update($data);
        $config->refresh();
        FileUploadConfigCache::set($config);
        return $result;
    }
}